package com.fight.strive.sys.modules.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fight.strive.sys.modules.exception.StriveException;
import com.fight.strive.sys.modules.mybatisplus.utils.MyBatisPlusUtils;
import com.fight.strive.sys.modules.rbac.constants.RbacAuthConstants;
import com.fight.strive.sys.modules.rbac.dao.RbacElemMapper;
import com.fight.strive.sys.modules.rbac.dto.RbacElemDto;
import com.fight.strive.sys.modules.rbac.entity.RbacElemEntity;
import com.fight.strive.sys.modules.rbac.service.RbacElemService;
import com.fight.strive.sys.modules.request.dto.PageRequest;
import com.fight.strive.sys.modules.response.dto.PageData;
import com.fight.strive.sys.modules.sysadmin.utils.SysAdminUtils;
import com.fight.strive.sys.utils.BeanUtils;
import com.fight.strive.sys.utils.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * @author ZHOUXIANG
 */
@Service
@Slf4j
public class RbacElemServiceImpl
        extends ServiceImpl<RbacElemMapper, RbacElemEntity>
        implements RbacElemService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void save(@Valid RbacElemDto dto) {
        RbacElemEntity entity = this.getByCodeNotId(
                dto.getElemCode(), dto.getId());
        if (ObjectUtils.notNull(entity)) {
            throw new StriveException("该元素代码已经存在");
        }
        entity = new RbacElemEntity();
        BeanUtils.copyPropertiesIgnoreNull(dto, entity);
        this.saveOrUpdate(entity);
        // 更新缓存
        this.updateRedisData(entity);
    }

    @Override
    public RbacElemEntity getByCodeNotId(String code, Long id) {
        QueryWrapper<RbacElemEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("elem_code", code);
        if (ObjectUtils.notNull(id)) {
            queryWrapper.ne("id", id);
        }
        return this.getOne(queryWrapper);
    }

    @Override
    public PageData<RbacElemEntity> list(PageRequest<RbacElemDto> pageRequest) {
        QueryWrapper<RbacElemEntity> queryWrapper = new QueryWrapper<>();
        MyBatisPlusUtils.buildQuery(queryWrapper, pageRequest, "authCode");
        IPage<RbacElemEntity> page = pageRequest.buildMybatisPlusPage();
        IPage<RbacElemEntity> iPage = this.page(page, queryWrapper);
        return new PageData<>(iPage);
    }

    @Override
    public void delete(RbacElemDto dto) {
        // 删除缓存
        this.deleteRedisData(this.getElemById(dto.getId()));
        // 删除数据库
        this.removeById(dto.getId());
    }

    @Override
    public void deleteBatch(List<Long> ids) {
        // 删除缓存
        for (Long id : ids) {
            RbacElemEntity entity = this.getElemById(id);
            this.deleteRedisData(entity);
        }
        // 删除数据库
        this.removeByIds(ids);
    }

    @Override
    public RbacElemEntity getElemById(Long elemId) {
        RbacElemEntity entity = this.getRedisData(
                RbacAuthConstants.ELEM_ID_KEY, elemId);
        if (ObjectUtils.isNull(entity)) {
            // 读取数据库
            entity = this.getById(elemId);
            // 存入 redis
            this.updateRedisData(entity);
        }
        return entity;
    }

    @Override
    public RbacElemEntity getElemByCode(String code) {
        Long tenantId = SysAdminUtils.getCurrentTenantId();
        RbacElemEntity entity = this.getRedisData(
                RbacAuthConstants.ELEM_CODE_ID_KEY
                        .concat(String.valueOf(tenantId)), code);
        if (ObjectUtils.isNull(entity)) {
            QueryWrapper<RbacElemEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("elem_code", code);
            entity = this.getOne(queryWrapper, false);
            if (ObjectUtils.notNull(entity)) {
                this.updateRedisData(entity);
            }
        }
        return entity;
    }

    @Override
    public void updateRedisData(RbacElemEntity entity) {
        // elem id -> entity
        redisTemplate.opsForHash().put(
                RbacAuthConstants.ELEM_ID_KEY, entity.getId(), entity);
        // elem code -> elem id
        redisTemplate.opsForHash().put(
                RbacAuthConstants.ELEM_CODE_ID_KEY
                        .concat(String.valueOf(entity.getTenantId())),
                entity.getElemCode(), entity.getId());
    }

    @Override
    public RbacElemEntity getRedisData(String key, Object hashKey) {
        if (RbacAuthConstants.ELEM_ID_KEY.equals(key)) {
            return (RbacElemEntity) redisTemplate.opsForHash().get(
                    RbacAuthConstants.ELEM_ID_KEY, hashKey);
        } else {
            Long elemId = (Long) redisTemplate.opsForHash().get(key, hashKey);
            if (ObjectUtils.notNull(elemId)) {
                return (RbacElemEntity) redisTemplate.opsForHash().get(
                        RbacAuthConstants.ELEM_ID_KEY, elemId);
            }
        }
        return null;
    }

    @Override
    public void deleteRedisData(RbacElemEntity entity) {
        redisTemplate.opsForHash().delete(
                RbacAuthConstants.ELEM_ID_KEY, entity.getId());
        redisTemplate.opsForHash().delete(
                RbacAuthConstants.ELEM_CODE_ID_KEY
                        .concat(String.valueOf(entity.getTenantId())),
                entity.getElemCode());
    }
}
